package me.seu.demo.service.operate;

import lombok.extern.slf4j.Slf4j;
import me.seu.demo.test.hex.ByteArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 开工模型 V2
 *
 * @author liangfeihu
 * @since 2022/9/5 11:43
 */
@Slf4j
public class OpUtilV2 {

    public static List<Integer> getExcelDataList(XSSFWorkbook workbook, int sheetIndex) throws Exception {
        // 获得当前sheet工作表
        XSSFSheet sheet = workbook.getSheetAt(sheetIndex);
        if (sheet == null) {
            throw new RuntimeException("sheet not allow null");
        }
        // 获得当前sheet的开始行
        int firstRowNum = sheet.getFirstRowNum();

        // 获得当前sheet的结束行
        int lastRowNum = sheet.getLastRowNum();
        if (lastRowNum < 2) {
            throw new RuntimeException("no sheet data to handle");
        }
        log.info("excel firstRowNum={} lastRowNum={}", firstRowNum, lastRowNum);

        List<Integer> dataList = new ArrayList<>();
        for (int index = 1; index <= lastRowNum; index++) {
            Row dataRow = sheet.getRow(index);
            if (dataRow == null) {
                throw new RuntimeException("excel row is null");
            }

            try {
                Cell cell = dataRow.getCell(2);
                String strValue = POIUtil.getCellValue(cell);
                if (StringUtils.isBlank(strValue)) {
                    break;
                }
                String[] split = strValue.split(",");
                for (String str : split) {
                    int integerValue = ByteArrayUtils.covert(str.toUpperCase());
                    dataList.add(integerValue);
                }
            } catch (Exception e) {
                log.error("parse error, index={}", index, e);
            }
        }

        return dataList;
    }


    public static Map<Integer, List<Integer>> getExcelDataMap(XSSFWorkbook workbook, int sheetIndex) throws Exception {
        // 获得当前sheet工作表
        XSSFSheet sheet = workbook.getSheetAt(sheetIndex);
        if (sheet == null) {
            throw new RuntimeException("sheet not allow null");
        }
        // 获得当前sheet的开始行
        int firstRowNum = sheet.getFirstRowNum();

        // 获得当前sheet的结束行
        int lastRowNum = sheet.getLastRowNum();
        if (lastRowNum < 2) {
            throw new RuntimeException("no sheet data to handle");
        }
        log.info("excel firstRowNum={} lastRowNum={}", firstRowNum, lastRowNum);

        Map<Integer, List<Integer>> accMap = new HashMap<>();
        for (int index = 1; index <= lastRowNum; index++) {
            Row dataRow = sheet.getRow(index);
            if (dataRow == null) {
                throw new RuntimeException("excel row is null");
            }

            List<Integer> accList = new ArrayList<>();
            try {
                Cell cell = dataRow.getCell(2);
                String strValue = POIUtil.getCellValue(cell);
                if (StringUtils.isBlank(strValue)) {
                    break;
                }
                String[] split = strValue.split(",");
                for (String str : split) {
                    int integerValue = ByteArrayUtils.covert(str.toUpperCase());
                    accList.add(integerValue);
                }
            } catch (Exception e) {
                log.error("parse error, index={}", index, e);
            }

            accMap.put(index, accList);
        }

        return accMap;
    }

    public static void outputHandleExcel(XSSFWorkbook workbook, Integer workThreshold, Integer maxMinDiff, String fileName, int sheetIndex) throws Exception {
        Map<Integer, List<Integer>> excelDataMap = getExcelDataMap(workbook, sheetIndex);

        // 获得当前sheet工作表
        XSSFSheet sheet = workbook.getSheetAt(sheetIndex);
        // 获得当前sheet的结束行
        int lastRowNum = sheet.getLastRowNum();
        for (int index = 1; index <= lastRowNum; index++) {
            Row dataRow = sheet.getRow(index);
            if (dataRow == null) {
                throw new RuntimeException("excel row is null");
            }

            Cell cell = dataRow.getCell(2);
            String strValue = POIUtil.getCellValue(cell);
            if (StringUtils.isBlank(strValue)) {
                break;
            }

            List<Integer> dataList = excelDataMap.get(index);
            dataRow.createCell(5).setCellValue(OpModelUtil.judgeWorkStatus(dataList, workThreshold, maxMinDiff) ? "1" : "0");
        }

        //导出excel文件
        try {
            File file = new File(fileName);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            workbook.write(fileOutputStream);
            fileOutputStream.close();
            System.out.println("========文件导出已完成========");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("IO Erro" + e.getMessage());
        }
        workbook.close();
    }


    public static void main(String[] args) throws Exception {
        XSSFWorkbook workbook = new XSSFWorkbook(OpUtilV2.class.getClassLoader().getResourceAsStream("excel/oee_4_1.xlsx"));
        // excel sheet序号，默认从0开始
        int sheetIndex = 2;

        // 1. 读取Excel数据
        List<Integer> dataList = getExcelDataList(workbook, sheetIndex);
        log.info("excel data list={}", dataList);

        WorkModel workModel = OpModelUtilV3.getWorkThreshold(dataList);
        log.info("sheetIndex" + (sheetIndex + 1) + " workThreshold=" + workModel.getWorkThreshold() + " : maxMinDiff=" + workModel.getMaxMinDiff());

        // 5. 输出判断结果到excel
        outputHandleExcel(workbook, workModel.getWorkThreshold(), workModel.getMaxMinDiff(), "./oee_sheet" + (sheetIndex + 1) + ".xlsx", sheetIndex);
    }

}
